package cn.larry.common.blockchain;

import java.security.MessageDigest;
import java.util.List;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2024/10/11 11:34
 *
 * @Version 1.0
 */
public class StringUtil {
    public static String applySha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getJson(List<Block> blockchain) {
        if (blockchain == null || blockchain.size() < 1)
            return "";
        StringBuilder sb = new StringBuilder();
        for (Block bean : blockchain) {
            if(bean==null)
                break;
            sb.append(bean.toString()).append(",\n");
        }
        // 移除最后的逗号和空格
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 2);
        }
        return sb.toString();
    }
}
